package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.Car;
import com.yld.car.domain.MyCarMarketInfo;
import com.yld.car.domain.MyPublishCarInfo;
import com.yld.car.domain.ReflushStateInfo;
import com.yld.car.domain.UserInfo;
import com.yld.car.service.TimerService;

public class MyCarMarketActivity extends BaseActivity implements
		OnItemClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.publish);
		TextView titleText = (TextView) findViewById(R.id.title);
		utils = NetworkProgressUtils.getInstance();
		titleText.setText("发布车源");
		// initView();
		startService(new Intent(this, TimerService.class));
		list1 = (ListView) findViewById(R.id.list1);
		list1.setOnItemClickListener(this);
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		marketInfo = (MyCarMarketInfo) readObject("myCarMarketInfo");
		showBackButton();
		// new MyPublishCarInfoTask(false).execute("");
	}

	public void initView() {
		Button button1 = (Button) findViewById(R.id.rightButton1);
		button1.setVisibility(View.VISIBLE);
		Button button2 = (Button) findViewById(R.id.rightButton2);
		button2.setVisibility(View.VISIBLE);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		new MyPublishCarInfoTask(false).execute("");
	}

	private ProgressBar mBar;
	private NetworkProgressUtils utils;

	public void onAction(View v) {
		int id = v.getId();

		switch (id) {
		case R.id.publishButton:
			Intent intent = new Intent();
			intent.setClass(this, MyCarPublishActivity.class);
			startActivity(intent);

			break;

		case R.id.reflushButton:
			new Thread(new Runnable() {

				@Override
				public void run() {

					reflush();
				}
			}).start();

			break;

		case R.id.filterButton:
			intent = new Intent();
			intent.setClass(this, FilterBrandActivity.class);
			startActivityForResult(intent, 1);
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (1 == requestCode && RESULT_OK == resultCode) {

			String brandName = data.getStringExtra("brandName");

			mBrandName = brandName;
			new MyPublishCarInfoTask(true).execute("");
		}

	}

	private void reflush() {

		ReflushStateInfo rsi = (ReflushStateInfo) readObject("reflush");

		if (rsi == null || rsi.isReflush()) {
			HashMap<String, String> allParams = new HashMap<String, String>();
			String userId = null;
			if (marketInfo == null) {
				userId = ((UserInfo) readObject("userInfo")).getUserId();
			} else {
				userId = marketInfo.getUserId();
			}
			allParams.put("userId", userId);

			utils = NetworkProgressUtils.getInstance();
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(14),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(14),
					ConstantUtils.GET_BATCH_REFRESH_URL, allParams);

			Message msg = mHandler.obtainMessage();
			msg.what = REFLUSH;
			msg.obj = o;

			mHandler.sendMessage(msg);
		} else {
			Message msg = mHandler.obtainMessage();
			msg.what = REFLUSH_REFUSE;
			msg.obj = "";
			mHandler.sendMessage(msg);
		}

		// System.out.println("reflush==" + o);
	}

	private static final int REFLUSH = 1;
	private static final int REFLUSH_REFUSE = 2;

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			int what = msg.what;
			Object o = msg.obj;
			if (o == null)
				return;
			if (REFLUSH == what) {

				if (o.toString().indexOf("刷新成功") >= 0) {
					Toast.makeText(MyCarMarketActivity.this, "刷新成功",
							Toast.LENGTH_SHORT).show();
					ReflushStateInfo rsi = new ReflushStateInfo();
					rsi.setReflush(false);
					writeObject(rsi, "reflush");
					new MyPublishCarInfoTask(false).execute("");
				} else {
					Toast.makeText(MyCarMarketActivity.this, "刷新失败",
							Toast.LENGTH_SHORT).show();
				}

			} else if (REFLUSH_REFUSE == what) {
				//
				showDialogFinish("亲，刷新功能每小时只能使用一次哦......", false);
				// Toast.makeText(MyCarMarketActivity.this, o.toString(),
				// Toast.LENGTH_SHORT).show();
			}
		}
	};
	private ListView list1;

	private MyCarMarketInfo marketInfo = null;

	private String mBrandName = "";

	private class MyPublishCarInfoTask extends
			AsyncTask<String, String, ArrayList<Car>> {

		public MyPublishCarInfoTask(boolean flag) {
			this.flag = flag;
		}

		private boolean flag;

		@Override
		protected ArrayList<Car> doInBackground(String... params) {

			publishProgress("");
			/**
			 * GetCarsByUserId(string userId, string nowPage, string pageSize,
			 * string brandName)
			 * 
			 * 参数一：userId:当前登录用户的ID 参数二：nowPage:当前页码，（数参数值例如：“1”）
			 * 参数三：pageSize:每页显示条数，（参数值例如：“20”） 参数四：brandName:品牌名称
			 */
			HashMap<String, String> allParams = new HashMap<String, String>();
			String userId = null;
			String nowPage = null;
			String pageSize = null;
			String brandName = null;
			if (marketInfo == null) {
				UserInfo userInfo = (UserInfo) readObject("userInfo");
				userId = userInfo.getUserId();
				nowPage = "1";
				pageSize = "20";
				brandName = "奔驰";
			} else {
				userId = marketInfo.getUserId();
				nowPage = marketInfo.getNowPage() + "";
				pageSize = marketInfo.getPageSize() + "";

			}

			if (flag) {
				brandName = mBrandName;
			}
			System.out.println("brandName==" + brandName);
			allParams.put("userId", userId);
			allParams.put("nowPage", nowPage);
			allParams.put("pageSize", pageSize);
			allParams.put("brandName", brandName);
			utils = NetworkProgressUtils.getInstance();
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(15),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(15),
					ConstantUtils.GET_ADD_NEW_CARS_URL, allParams);
			System.out.println("======publisher==>" + o);

			if ("exception".equals(o)) {

				return null;
			}
			ArrayList<Car> all = utils.parseJson(o.toString(), "table",
					NetworkProgressUtils.MY_PUBLISH_CAR_INFO_TYPE,false);

			// System.out.println("all===>ß" + all);
			return all;
		}

		@Override
		protected void onProgressUpdate(String... values) {

			super.onProgressUpdate(values);

		}

		@Override
		protected void onPreExecute() {

			list1.setVisibility(View.GONE);
			mBar.setVisibility(View.VISIBLE);

			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {

			super.onPostExecute(result);
			list1.setVisibility(View.VISIBLE);
			mBar.setVisibility(View.GONE);
			if (result != null) {

				MyPublishCarInfoAdapter adapter = new MyPublishCarInfoAdapter(
						result);
				list1.setAdapter(adapter);
			} else {
				Toast.makeText(MyCarMarketActivity.this, "服务器取数据异常...",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	private class MyPublishCarInfoAdapter extends BaseAdapter {

		private ArrayList<Car> all;

		public MyPublishCarInfoAdapter(ArrayList<Car> all) {
			this.all = all;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return all.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return all.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_items, null);
			}

			Car c = all.get(position);

			if (c instanceof MyPublishCarInfo) {

				ImageView image = (ImageView) convertView
						.findViewById(R.id.itemCarImage);

				MyPublishCarInfo myPublishCarInfo = (MyPublishCarInfo) c;

				// 获取类型
				String type = myPublishCarInfo.getQhtime();
				if ("".equals(type)) {
					image.setImageResource(R.drawable.xianhuo);

				} else {
					image.setImageResource(R.drawable.qihuo);
				}
				// TextView typeText1 = (TextView) convertView
				// .findViewById(R.id.itemCarImage);
				// typeText1.setText(myPublishCarInfo.getXiliename());
				// TextView typeText = (TextView) convertView
				// .findViewById(R.id.itemType);
				// //typeText.setText(myPublishCarInfo.getXhorgh());
				// TextView titleText = (TextView) convertView
				// .findViewById(R.id.itemTitle);
				//
				// titleText.setText(myPublishCarInfo.getPinpainame());
				// TextView abbreviationText = (TextView) convertView
				// .findViewById(R.id.itemAbbreviation);

				TextView typeText = (TextView) convertView
						.findViewById(R.id.itemType);
				typeText.setVisibility(View.VISIBLE);
				typeText.setText(myPublishCarInfo.getPinpainame() + "-"
						+ myPublishCarInfo.getXiliename());
				// TextView titleText = (TextView) convertView
				// .findViewById(R.id.itemTitle);
				//
				// titleText.setText(s.getPinpainame());
				TextView abbreviationText = (TextView) convertView
						.findViewById(R.id.itemAbbreviation);

				// abbreviationText.setText(s.getName());
				abbreviationText.setText(myPublishCarInfo.getName());
				TextView priceText = (TextView) convertView
						.findViewById(R.id.itemPrice);

				priceText.setText(myPublishCarInfo.getPress() + "万");
				TextView configText = (TextView) convertView
						.findViewById(R.id.itemSelectConfig);

				configText.setText(myPublishCarInfo.getXppz());
				TextView publishText = (TextView) convertView
						.findViewById(R.id.itemPublishDate);

				String date = myPublishCarInfo.getAdddate();

				date = date.substring(0, date.indexOf(" ") + 1);
				publishText.setText(date);
				TextView dealerText = (TextView) convertView
						.findViewById(R.id.itemDealerName);
				dealerText.setText(myPublishCarInfo.getCompanyname());
			}

			convertView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return convertView;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		MyPublishCarInfo myPublishCarInfo = (MyPublishCarInfo) adapterView
				.getAdapter().getItem(position);

		// System.out.println("onItem=="+myPublishCarInfo.getName());
		// System.out.println("=====type====" + myPublishCarInfo.getXhorgh());
		String time = myPublishCarInfo.getQhtime();
		String type = "";
		if (time.equals("")) {
			type = "现货";
		} else {
			type = "期货";
		}
		Intent intent = new Intent();
		intent.setClass(this, CarDetailInfoActivity.class);
		intent.putExtra("cId", myPublishCarInfo.getId());

		intent.putExtra("carName", myPublishCarInfo.getPinpainame());

		intent.putExtra("carType", type);// 类型
		intent.putExtra("carSeries", myPublishCarInfo.getXiliename()); // 传入一个车源所属者的状态
		intent.putExtra("price", myPublishCarInfo.getPress());
		intent.putExtra("isMyself", true);
		startActivity(intent);
	}

}
